﻿using System;
using System.Web.UI;

namespace PD.Web.DynamicData.FieldTemplates
{
    /// <summary>
    /// Represents the URL field template control.
    /// </summary>
    public partial class UrlField : System.Web.DynamicData.FieldTemplateUserControl
    {
        /// <summary>
        /// Gets the data control that handles the data field in a field template.
        /// </summary>
        /// <returns>A data control that handles the data field in a field template.</returns>
        public override Control DataControl
        {
            get
            {
                return this.HyperLinkUrl;
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.DataBinding"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnDataBinding(EventArgs e)
        {
            this.HyperLinkUrl.NavigateUrl = this.ProcessUrl(this.FieldValueString);
        }

        /// <summary>
        /// Processes the URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns>The processed URL.</returns>
        private string ProcessUrl(string url)
        {
            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                return url;
            }

            return "http://" + url;
        }
    }
}
